import { PropType } from 'vue';
import useLegend from './useLegend';
import { EChartOption } from 'echarts';
import { TLegend } from './types';
import './index.scss';

export const MciChartLegend = defineComponent({
  props: {
    option: {
      type: Object as PropType<EChartOption>,
      default: () => ({})
    },
    legendData: {
      type: Array as PropType<TLegend[]>,
      default: () => []
    },
    legendClickable: {
      type: Boolean,
      default: true
    }
  },
  emits: ['click'],
  setup(props, { emit }) {
    const legendData = ref<TLegend[]>([]);

    const { getLegendData } = useLegend();

    watchEffect(() => {
      legendData.value = (getLegendData(props.option) || []) as TLegend[];
    });

    const data = computed(() => {
      return props.legendData.length ? props.legendData : legendData.value;
    });

    const hiddenSeriesNames = ref<string[]>([]);

    const onClick = (name: string) => {
      if (!hiddenSeriesNames.value.includes(name)) {
        hiddenSeriesNames.value.push(name);
      } else {
        hiddenSeriesNames.value = hiddenSeriesNames.value.filter((item) => item !== name);
      }
      emit('click', hiddenSeriesNames.value);
    };

    return () => (
      <div class="flex justify-center">
        {data?.value.map((item) => {
          if (!item) return '';
          return (
            <div
              class={[
                'flex items-center ml-12 justify-between',
                {
                  'cursor-pointer': props.legendClickable,
                  'hidden-legend': hiddenSeriesNames.value.includes(item.label)
                }
              ]}
              key={item.label}
              onClick={() => (props.legendClickable ? onClick(item.label) : null)}>
              {item.type === 'line' ? (
                <p class="w-8 h-2" style={{ backgroundColor: item.color }}></p>
              ) : (
                <p class="w-8 h-8 rounded-2px" style={{ backgroundColor: item.color }}></p>
              )}
              <p class="text-value-12_bold cr-white-064 ml-8">{item.label}</p>
            </div>
          );
        })}
      </div>
    );
  }
});
